package com.ruoyi.common.client;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

@Slf4j
@Component
public class MovieClient {

    public R postRequest(String url, Map<String, Object> params, Class clazz) {
        if (!params.isEmpty()) {
            url = url + "?" + HttpUtil.toParams(params);
        }
        log.info("请求地址：{}", url);
        HttpResponse execute = HttpUtil.createPost(url).setConnectionTimeout(500).execute();
//        String post = HttpUtil.post(url, params);
        return HttpResponseUtil(execute, clazz);
    }

    public R postRequest1(String url, Map<String, Object> params, Class clazz) {
        if (!params.isEmpty()) {
            url = url + "?" + HttpUtil.toParams(params);
        }
        log.info("请求地址：{}", url);
        Map<String, Object> map = new HashMap<>();
        map.put("badw", "重庆");

        String json = JSON.toJSONString(map);
        HttpResponse execute = HttpUtil.createPost(url).body(json).setConnectionTimeout(500).execute();
        return HttpResponseUtil(execute, clazz);
    }

    /**
     * 解析返回值
     */
    public static R HttpResponseUtil(HttpResponse execute, Class clazz) {
        if (execute.isOk()) {
            String body = execute.body();
            log.debug("返回参数{}", body);
            return R.ok(JSON.parseObject(body, clazz));
        } else {
            StringBuilder message = new StringBuilder();
            try {
                log.info("请求接口失败，状态码：{}，返回内容：{}", execute.getStatus(), execute.body());
                JSONObject jsonObject = JSON.parseObject(execute.body());
                jsonObject.keySet().forEach(key -> {
                    message.append(jsonObject.getJSONObject(key).getString("message"));
                });
            } catch (Exception e) {
                throw new RuntimeException("国家电电影剧接口异常" + message);
            }
        }
        throw new RuntimeException("国家电电影剧接口异常");
    }
}
